import type { TableFieldsOption } from "@anlib/sqlite-orm/lib/types";
import SqliteHelper from "@/sqlite/SqliteHelper";
import type { DatabaseParams } from "react-native-sqlite-storage";

// 测试
const databaseParams: DatabaseParams = {
  name: "test.db",
  location: "default"
};

// 本地保存的字段数据, 具体类型见下面 TagPoolItemType 定义
const fields: TableFieldsOption[] = [
  { field: "id", type: "INTEGER", isKey: true },
  { field: "name", type: "TEXT", isNotNull: true },
  { field: "age", type: "INTEGER", isNotNull: true },
  { field: "height", type: "FLOAT" },
  { field: "weight", type: "FLOAT" },
  { field: "createTime", type: "TEXT" },
];

// 初始化 sqlite
let sqlh: SqliteHelper | null = null;
const initSqlite = (): Promise<SqliteHelper> => {
  return new Promise((resolve, reject) => {
    const instance = new SqliteHelper(databaseParams, fields, 2);

    // 版本更新
    instance.updateVersion = async (oldVersion, newVersion) => {
      try {

        // 旧版本为1则删除表, 重新创建
        if (oldVersion === 1) {
          console.log("删除原先表的数据");
          await instance.deleteTable();
        }
        // BUG Android 11 无法触发回调
        console.log("重新创建表");
        await instance.createTable();
      } catch (error) {
        // TODO
        console.log("数据库更新失败");
        console.log("error: ", error);
      }
      return Promise.resolve();
    };

    // 初始化
    instance
      .init()
      .then(res => {
        if (res instanceof SqliteHelper) {
          sqlh = res;
          resolve(sqlh);
        } else {
          reject(res);
        }
      })
      .catch(err => {
        reject(err);
      });
  });
};

// 关闭数据库
const closeSqlite = () => {
  if (sqlh) {
    sqlh.close();
    sqlh = null;
  }
};

// 定义sqling 数据的 ts 类型
type TestSqliteType = {
  /** 数据库ID */
  id: number;

  /** 姓名 */
  name: string;

  /** 年龄 */
  age: number;

  /** 年龄 */
  height?: number;

  /** 年龄 */
  weight?: number;

  /** 创建时间 */
  createTime?: string;
};

export { sqlh, initSqlite, closeSqlite, type TestSqliteType };
